package cn.kow.kmall.system.service.impl;

import cn.kow.kmall.common.constant.KmallConstants;
import cn.kow.kmall.common.enums.KmallResultEnum;
import cn.kow.kmall.core.constant.KmallStatusConstant;
import cn.kow.kmall.core.exception.ServiceException;
import cn.kow.kmall.system.entity.SysUser;
import cn.kow.kmall.system.repository.SysUserRepository;
import cn.kow.kmall.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2019-10-29 18:27
 * @Modified By:
 */
@Slf4j
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserRepository sysUserRepository;

    @Override
    public void save(SysUser user) {
        String username = user.getUsername();
        if (StringUtils.isEmpty(username)) {
            throw new ServiceException(KmallConstants.FAIL, "用户名不能为空");
        }
        // 用户名查重
        if (isUsernameExist(username)) {
            throw new ServiceException(KmallConstants.FAIL, "用户名已存在");
        }
        user.setNickname(StringUtils.isEmpty(user.getNickname()) ? username : user.getNickname());
        sysUserRepository.create(user);
    }

    @Override
    public void remove(Long userId) {
        sysUserRepository.deleteById(userId);
    }

    @Override
    public void update(SysUser user) {
        SysUser sysUser = findByUserName(user.getUsername());
        if (StringUtils.isNotEmpty(user.getNickname())) {
            sysUser.setNickname(user.getNickname());
        }
        if (StringUtils.isNotEmpty(user.getEmail())) {
            sysUser.setEmail(user.getEmail());
        }
        if (StringUtils.isNotEmpty(user.getPhone())) {
            sysUser.setPhone(user.getPhone());
        }
        if (StringUtils.isNotEmpty(user.getAvatar())) {
            sysUser.setAvatar(user.getAvatar());
        }
        sysUser.setGender(user.getGender());
        sysUser.setUpdateBy(user.getUpdateBy());
        sysUserRepository.update(user);
    }

    @Override
    public void enableUser(Long userId) {
        SysUser user = sysUserRepository.findById(userId)
                .orElseThrow(() -> new ServiceException(KmallResultEnum.USER_NOT_FIND));
        user.setStatus(KmallStatusConstant.NORMAL);
        sysUserRepository.update(user);
    }

    @Override
    public void lockUser(Long userId) {
        SysUser user = sysUserRepository.findById(userId)
                .orElseThrow(() -> new ServiceException(KmallResultEnum.USER_NOT_FIND));
        user.setStatus(KmallStatusConstant.DISABLE);
        sysUserRepository.update(user);
    }

    @Override
    public void unlockUser(Long userId) {
        SysUser user = sysUserRepository.findById(userId)
                .orElseThrow(() -> new ServiceException(KmallResultEnum.USER_NOT_FIND));
        user.setStatus(KmallStatusConstant.NORMAL);
        sysUserRepository.update(user);
    }

    /**
     * 用户名是否存在
     * @param username  用户名
     * @return  结果
     */
    private boolean isUsernameExist(String username) {
        try {
            SysUser sysUser = findByUserName(username);
            if (null == sysUser) {
                return false;
            }
            return true;
        } catch (ServiceException e) {
            return false;
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public SysUser findByUserName(String username) {
        if (StringUtils.isEmpty(username)) {
            throw new ServiceException(KmallConstants.FAIL, "用户名不能为空");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        Optional<SysUser> optional = sysUserRepository.findOne(Example.of(sysUser));
        return optional.orElseThrow(() -> new ServiceException(KmallResultEnum.USER_NOT_FIND));
    }

    @Override
    public Page<SysUser> listUserByPage(String username, String phone, Short status, Pageable pageable) {
        Page<SysUser> list = sysUserRepository.findAll(new Specification<SysUser>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (StringUtils.isNotBlank(username)) {
                    predicates.add(criteriaBuilder.like(root.get("username"), "%" + username + "%"));
                }
                if (StringUtils.isNotBlank(phone)) {
                    predicates.add(criteriaBuilder.equal(root.get("phone"), phone));
                }
                if (null != status) {
                    predicates.add(criteriaBuilder.equal(root.get("status"), status));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        }, pageable);
        return list;
    }

}
